/**
 * Copyright (C) 2011 KingCore Science & Technology CO,.LTD. All rights reserved.
 * XNS PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

/**
 * Copyright (C) 2002-2011 WUZEWEN. All rights reserved.
 * WUZEWEN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 * This software is the confidential and proprietary information of
 * WuZeven, Personal. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with WuZeven.
 */

package com.kingcore.director.reminder.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Event;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.lang.reflect.Modifier;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Observable;
import java.util.ResourceBundle;
import java.util.Vector;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;

import org.apache.log4j.Logger;

import wzw.beans.CodeNameBean;
import wzw.swing.table.PlainTable;
import wzw.swing.table.PlainTableModel;
import wzw.swing.tree.PlainTree;
import wzw.swing.tree.PlainTreeModel;
import wzw.util.ComponentUtil;
import wzw.util.I18nUtil;
import wzw.util.I18nUtils;
import wzw.util.StringUtils;

import com.kingcore.director.DirectorConstants;
import com.kingcore.director.base.ui.DirectorMenuBar;
import com.kingcore.director.base.ui.DirectorPanel;
import com.kingcore.director.base.ui.DirectorToolBar;
import com.kingcore.director.core.ui.CommonSearchPanel;
import com.kingcore.director.core.ui.CommonSearchable;
import com.kingcore.director.core.util.DirectorComponentUtils;
import com.kingcore.director.core.util.DirectorStringUtils;
import com.kingcore.director.core.util.Formatter;
import com.kingcore.director.main.Main;
import com.kingcore.director.main.MainFrame;
import com.kingcore.director.reminder.bean.AwokeBean;
import com.kingcore.director.reminder.clock.Timer;
import com.kingcore.director.reminder.clock.TimerTask;
import com.kingcore.director.reminder.dao.ReminderDao;
import com.kingcore.director.reminder.dao.impl.ReminderDaoImpl;
import com.kingcore.director.setting.bean.FilesBackupBean;
import com.kingcore.framework.context.ApplicationContext;

/**
 * <p>java class file describe</p>
 * @author Zeven on 2006-2-25
 * @version	1.0
 * @see		Object#equals(java.lang.Object)
 * @since	JDK5
 */
public class ReminderMainPanel extends DirectorPanel 
	implements ActionListener,
	MouseListener, MouseMotionListener, CommonSearchable, KeyListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	//log object
	private final static Logger log = Logger.getLogger(ReminderMainPanel.class);

	static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	static SimpleDateFormat sdfShort=new SimpleDateFormat("yyyy-MM-dd");

	private static final int MainTable_Column_Count = 5;
	private static final int MainTable_Column_Index_Name = 0;
	private static final int MainTable_Column_Index_NextTime = 1;
	private static final int MainTable_Column_Index_Interval = 2;
	private static final int MainTable_Column_Index_Confirm = 3;
	private static final int MainTable_Column_Index_Content = 4;
	public static final int[] MainTable_Columns_Width = {239,153,90,60, Main.MainFrame_Size_Width-239-153-90-90};
	public static final String[] MainTable_Headers = {"Name", "NextTime", "Interval", "Confirm", "Content"};
 
	Timer timer =null;
	private MainFrame mainFrame = null; 
	private JSplitPane mainSplitPane = null; // JSplitPane
	private static final int MainSplitPane_Left_Width= Main.MainFrame_Size_Width/6;
	
	private JScrollPane leftScrollPanel=null;
	private JScrollPane rightScrollPanel=null;
	private PlainTree tree = null;
	private PlainTable mainTable = null;
	
	private JPopupMenu popupMenuForTable = null;	//JTable 的 JPopupMenu
	private JMenuItem jpmi_MainTable_New = null;
	private JMenuItem jpmi_MainTable_Edit = null;
	private JMenuItem jpmi_MainTable_Delete = null;
	private JMenuItem jpmi_MainTable_Disable = null;
	private JMenuItem jpmi_MainTable_Search = null;
	private JMenuItem jpmi_MainTable_Refresh = null;
	private JMenuItem jpmi_MainTable_Test = null;

	public static final String Reminder_Type_Garbage="99";
	public static final String Reminder_Type_AllCurrent="00";

	/**
	 * 
	 * @param e
	 */
	public void thisResized(java.awt.event.ComponentEvent e){
		int width=new Double(leftScrollPanel.getParent().getSize().getWidth()).intValue();
		int height=new Double(leftScrollPanel.getParent().getSize().getHeight()).intValue()-5;	//5=toolBar's height
		//System.out.println("w="+width+" h="+height);

		// 5=toolBar's height    2=距左右边界宽度     1=组件相互之间的宽度
		leftScrollPanel.setBounds(new java.awt.Rectangle(2,this.mainFrame.clientTop,150, height) );
		//centerBar.setBounds(new java.awt.Rectangle(150 +2+1, this.clientTop,4, height) );
		rightScrollPanel.setBounds(new java.awt.Rectangle(150+2+1 +4,this.mainFrame.clientTop,width -(150+2+1 +4) -2, height));
		
		//getRightPane().setDividerLocation(600);
		
		leftScrollPanel.setViewportView(getTree());
		rightScrollPanel.setViewportView(getMainTable());
	}

	/**
	 * Table的弹出式菜单
	 */
	private JPopupMenu getPopupMenuForTable(){
		
		if(popupMenuForTable == null){
			popupMenuForTable = new JPopupMenu();
			
			jpmi_MainTable_New = new JMenuItem();
			jpmi_MainTable_New.setText("新建提醒");
			jpmi_MainTable_New.addActionListener( this );
			jpmi_MainTable_New.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_N,Event.CTRL_MASK) );
			jpmi_MainTable_Edit = new JMenuItem();
			jpmi_MainTable_Edit.setText("编辑提醒");
			jpmi_MainTable_Edit.addActionListener( this );
			jpmi_MainTable_Edit.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_M,Event.CTRL_MASK) );
			jpmi_MainTable_Delete = new JMenuItem();
			jpmi_MainTable_Delete.setText("删除提醒");
			jpmi_MainTable_Delete.addActionListener( this );
			jpmi_MainTable_Delete.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_D,Event.CTRL_MASK) );
			
			jpmi_MainTable_Test = new JMenuItem();
			jpmi_MainTable_Test.setText("测试提醒");
			jpmi_MainTable_Test.addActionListener( this );
			jpmi_MainTable_Test.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_T,Event.CTRL_MASK) );
			
			jpmi_MainTable_Disable = new JMenuItem();
			jpmi_MainTable_Disable.setText("批量停用");
			jpmi_MainTable_Disable.addActionListener( this );
			jpmi_MainTable_Disable.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_F,Event.CTRL_MASK) );

			jpmi_MainTable_Search = new JMenuItem();
			jpmi_MainTable_Search.setText("搜索...");
			jpmi_MainTable_Search.addActionListener( this );
			jpmi_MainTable_Search.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_F,Event.CTRL_MASK) );
			
			jpmi_MainTable_Refresh = new JMenuItem();
			jpmi_MainTable_Refresh.setText("Refresh");
			jpmi_MainTable_Refresh.addActionListener( this );
			jpmi_MainTable_Refresh.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_F5, Modifier.FINAL) );
			
			popupMenuForTable.add( jpmi_MainTable_New );
			popupMenuForTable.add( jpmi_MainTable_Edit );
			popupMenuForTable.add( jpmi_MainTable_Delete );
			popupMenuForTable.addSeparator();
			popupMenuForTable.add( jpmi_MainTable_Disable );
			popupMenuForTable.add( jpmi_MainTable_Search );
			popupMenuForTable.add( jpmi_MainTable_Refresh );
			popupMenuForTable.addSeparator();
			popupMenuForTable.add( jpmi_MainTable_Test );
			
		}
		
		return popupMenuForTable;
			
		
	}

	JSplitPane rightPanel = null;
	private JSplitPane getRightSplitPane() {
		if(rightPanel==null){
			rightPanel = new JSplitPane();

			rightPanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT, false);
			rightPanel.setBorder(null);	
			rightPanel.add(getCommonSearchPanel(), JSplitPane.TOP );	
			rightPanel.add(getRightScrollPane(), JSplitPane.BOTTOM );
			rightPanel.setOneTouchExpandable(true);
			rightPanel.setDividerSize(0);   //or rightPanel.setEnabled(false);
			rightPanel.setDividerLocation( CommonSearchPanel_Hight ); //Main.MainFrame_Size_Height-180
			
		}
		return rightPanel;
	}
 

	CommonSearchPanel searchPanel = null;
	private CommonSearchPanel getCommonSearchPanel() {

		if(searchPanel==null){
			searchPanel = new CommonSearchPanel(this, this.getMainTable() );
			this.mainFrame.getLanguageManager().addObserver(searchPanel);
		}
		return searchPanel;
	}
	
	/**
	 * This method initializes jPanel
	 *
	 * @return javax.swing.JPanel
	 */
	private JScrollPane getRightScrollPane() {
		if (rightScrollPanel == null) {
			rightScrollPanel = new JScrollPane();
			//rightScrollPanel.setBounds(new java.awt.Rectangle(158,this.clientTop,432, this.clientHeight));
			
			//rightScrollPanel.setLayout(new BorderLayout());
			//rightScrollPanel.setLayout( new BorderLayout() );
			rightScrollPanel.setViewportView(getMainTable());	//getRightPane()
			//rightScrollPanel.setBackground(Color.gray);
		}
		return rightScrollPanel;
	}


	/**
	 * This method initializes jTable	
	 * 	private
	 * @return javax.swing.JTable	
	 */
	public PlainTable getMainTable() {
		if (mainTable == null) {
			mainTable = new PlainTable();	


		    //System.out.println("-----1");
		    Object[][] data = {
		       {
		        "Jackson", new Integer(4),"1week","Y", "March 21"
		      }, {
		        "Zachary", new Integer(2),"3day","N", "May 12"
		      }
		    };
		    String[] headers = {
				      "名称", "提醒时间", "周期","需确认否","主要内容"
		    };

		    // A DefaultTableModel object is created and initialized with some
		    // data and headers.

		    //DefaultTableModel dtm = new DefaultTableModel(2, 3);
		    DefaultTableModel dtm = new DefaultTableModel(2, 3);
		    dtm.setDataVector(data, headers);
		    PlainTableModel sorter = new PlainTableModel( dtm, mainTable.getTableHeader());
		    sorter.setColumnClass(MainTable_Column_Index_NextTime, CodeNameBean.class);
		    
		    mainTable.setModel(sorter);//dtm);
		    mainTable.setGridColor(Color.LIGHT_GRAY);  //Color.BLUE
		    mainTable.setRowSelectionAllowed(true);
		    mainTable.setRowSelectionInterval(1, 1);	
		    mainTable.setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); //.SINGLE_SELECTION

		    mainTable.setShowGrid(true);
		    mainTable.getTableHeader().setReorderingAllowed(false);
		    mainTable.addMouseListener( this );
		    mainTable.addMouseMotionListener(this);
		    mainTable.addKeyListener(this);
		    
		    TableColumn tc = null;
		    TableColumnModel tcm = mainTable.getColumnModel(); 
	        for(int i=0; i < MainTable_Columns_Width.length; i++)   {
	            tc   =   tcm.getColumn(i);
	            tc.setPreferredWidth(MainTable_Columns_Width[i]); 
	        }
	        
//		    // 更改列宽度
//		    TableColumnModel cm = table.getColumnModel();
//		    cm.getColumn(0).setResizable(true);
//		    cm.getColumn(0).setWidth(150);
//		    cm.getColumn(1).setWidth(80);
//		    cm.getColumn(2).setWidth(300);

//		    table.getColumnModel().getColumn(0).setPreferredWidth( 330 );
//		    table.getColumnModel().getColumn(1).setPreferredWidth( 130 );
//			//table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
//			
//			//table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); 
//		    table.getColumnModel().getColumn(2).setPreferredWidth(530);
			
//			setAllColWith(table);
			
		    try {
				initTasksInfo("", true);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return mainTable;
	}
	
	/**
	 * This method initializes leftScrollPane
	 *
	 * @return javax.swing.JScrollPane
	 */
	private JScrollPane getLeftScrollPane() {
		if (leftScrollPanel == null) {
			leftScrollPanel = new JScrollPane();
			//leftScrollPanel.setBounds(new java.awt.Rectangle(2, this.clientTop,150, this.clientHeight));
			leftScrollPanel.setViewportView(getTree());	//getJt_tree()
		}
		return leftScrollPanel;
	}

	/**
	 * 
	 */
    DefaultMutableTreeNode root = null;
    DefaultMutableTreeNode dir = null;
    DefaultMutableTreeNode ord = null;
    DefaultMutableTreeNode imp = null;
    DefaultMutableTreeNode bri = null;
    DefaultMutableTreeNode ply = null;
	DefaultMutableTreeNode ait = null;
	DefaultMutableTreeNode els = null;
	DefaultMutableTreeNode gbg = null;

	public PlainTree getTree() {
		if (tree  == null) {
			//jTree = new JTree();
			//jTree.setBounds(new java.awt.Rectangle(7,7,154,241));
			//add wzw
		   
			//jtf = new JTextField(15);
		    //jtf.setEditable(false);

		    // Eight DefaultMutableTreeNode objects are created

		    root = 
		      new DefaultMutableTreeNode(new CodeNameBean("","WZW Director") );
		    
		    dir = 
		    		new DefaultMutableTreeNode( new CodeNameBean(Reminder_Type_AllCurrent,"我的提醒"));
		    
		    ord = 
		      new DefaultMutableTreeNode( new CodeNameBean("0000","普通提醒"));
		    imp = 
		      new DefaultMutableTreeNode( new CodeNameBean("0001","重要提醒"));
		    bri = 
		      new DefaultMutableTreeNode( new CodeNameBean("0002","生日"));
		    ply = 
		      new DefaultMutableTreeNode( new CodeNameBean("0003","日程、计划"));
			ait = 
			      new DefaultMutableTreeNode( new CodeNameBean("0004","约会"));
			els = 
			      new DefaultMutableTreeNode( new CodeNameBean("0005","其它"));
			

		    gbg = 
			      new DefaultMutableTreeNode( new CodeNameBean(Reminder_Type_Garbage,"垃圾箱"));

		    // The node hierarchy is loaded into a Default TreeModel object using
		    // the insertNodeInto() method.
		    
		    //wzw 
		    //dir.
		    
		    PlainTreeModel dtm = new PlainTreeModel(root);
		    dtm.insertNodeInto(dir, root, 0);
		    dtm.insertNodeInto(gbg, root, 1);
		    
		    dtm.insertNodeInto(ord, dir, 0);
		    dtm.insertNodeInto(imp, dir, 1);
		    dtm.insertNodeInto(bri, dir, 2);
		    dtm.insertNodeInto(ply, dir,3);
		    dtm.insertNodeInto(ait, dir,4);
		    dtm.insertNodeInto(els, dir,5);

		    //garbage下面的子节点
		    //dtm.insertNodeInto(ord, gbg, 0);
		    //dtm.insertNodeInto(imp, gbg, 1);
		    
		    //dtm.insertNodeInto(Bob, fin, 0);
		    //dtm.insertNodeInto(Sue, fin, 1);
		    //dtm.insertNodeInto(Joe, fin, 2);
		    
		    //dtm.insertNodeInto(Moe, acc, 0);

		    // A JTree object is created using the previously created
		    // Default TreeModel object.  Root handles are shown and the
		    // row at index 1 is expanded.

		    tree = new PlainTree(dtm);
            tree.setCellRenderer(new DirectorRenderer() );
		    tree.setShowsRootHandles(true);
		    tree.setRootVisible(false);
		    tree.setSelectionRow(0);// 0 is 我的提醒
		    tree.expandRow(0);
		    
		    // if there is a ScrollPanel,don't set Border again.
			//tree.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
		    tree.addMouseListener(new MainFrame_tree_mouseAdapter(this));
		    tree.addKeyListener(this);
		}
		return tree;
	}


	/**
	 * 系统备份任务管理初始
	 * @throws Exception
	 */
	private void initTasksInfo(String selectedType, boolean initTimer) throws Exception{
	
		Connection conn= null;
		Statement stmt =null;
		ResultSet rs=null;
		try {
//			String sourceURL="jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=E:/WZW_Documents/always_wzw/setting/Director/WUZEWEN/Director.mdb";     //DataBase是Access MDB文件的主文件名
//			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//			Connection conn2=DriverManager.getConnection(sourceURL);
//			Statement stmt2=conn2.createStatement();
//			ResultSet rset=stmt2.executeQuery("select a,b,c from AWOKE");
//			while(rset.next())
//			System.out.println(rset.getString(1));
			
			conn= ApplicationContext.getInstance().getDataSourceManager().getConnection();
			String userdataPath=null;
			//获取配置信息

			stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
			rs=stmt.executeQuery("SELECT val from "+DirectorConstants.SYS_Setting+" WHERE KEY='director.userdata.path'");
			if(rs.next()){
				userdataPath=rs.getString("val").toString();
			} else {
				log.error("cann't get user.data.path from table setting.");
				return ;
			}
			
			FilesBackupBean.setConfigPath(userdataPath);
			System.setProperty(MainFrame.User_Data_Path, userdataPath);
			
			//File f=new File("");
			//System.out.println(f.getAbsoluteFile().getAbsolutePath());
			//System.out.println( System.getProperty("user.dir") );
			System.setProperty(MainFrame.Direcotr_Home, System.getProperty("user.dir"));
			
			
//			// Task 1: print "boom", just for test.
//			TimerTask t1 = new TimerTask() {
//				public void run(){
//					log.debug("boom---");
//				}
//			};
//			// Task2: print current Time ,just for test.
//			TimerTask t2 = new TimerTask() { // Task 1: print "boom"
//				public void run(){
//					log.debug( Calendar.getInstance().getTime());
//				}
//			};	    
			// Create a timer, and schedule some tasks
			TimerTask tFileBuckup = null;
			if (initTimer) {
				timer = new Timer(true);
//				timer.schedule(t1,8000);     // boom every .5sec starting now
				
//				//主动垃圾回收，减少内存消耗
//				timer.scheduleAtFixedRate( new TimerTask(){
//					@Override
//					public void run() {
//						log.info("begin gc...");
//						System.gc();   //Java中没有任何机制保证程序能强制执行垃圾回收
//						log.info("end gc.");
//					}
//				}, 1000L*60*1, 1000L*60*1 );

				// Task3: backup file every day.
				//文件备份的任务
				tFileBuckup = new TimerTask() { // Task 1: print "boom"
					public void run(){
						try {
							FilesBackupBean.main(null);
						} catch (Exception e) {
							JOptionPane.showMessageDialog(null,e.getMessage(),"备份失败",JOptionPane.ERROR_MESSAGE);
							e.printStackTrace();
						}
					}
				};
			}
			
			sdf.applyPattern("yyyy-MM-dd");
			String strToday=sdf.format(new java.util.Date());
			String ts_time="08:15";	//"12:15";	//默认备份时间 每天12:15
			rs=stmt.executeQuery("SELECT val from "+DirectorConstants.SYS_Setting+" WHERE KEY='"+DirectorConstants.File_Backup_Time+"'");
			if(rs.next()){
				ts_time=rs.getString("val");
			}
			
			int intevHours=2;
			rs=stmt.executeQuery("SELECT val from "+DirectorConstants.SYS_Setting+" WHERE KEY='"+DirectorConstants.File_Backup_Interv+"'");
			if(rs.next()){
				intevHours= Integer.parseInt( rs.getString("val") );
			}
			strToday=strToday+" "+ts_time.trim()+":00";
			sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
			Date bakDay=Calendar.getInstance().getTime();
			bakDay=sdf.parse(strToday);
//			if(bakDay.before(Calendar.getInstance().getTime())){//时间过了不备份
//				//log.info("文件日备份任务已经超过时间："+strToday);	    	
//				bakDay.setDate(bakDay.getDate()+1);
//			}
			
			while(bakDay.before(Calendar.getInstance().getTime())){//时间过了不备份
				//log.info("文件日备份任务已经超过时间："+strToday);	    	
				bakDay.setHours( bakDay.getHours()+ intevHours );
			}

			if (initTimer) {
				log.info("Add: 添加文件备份任务，开始时间："+ sdf.format(bakDay)+"，间隔 "+intevHours+"小时。从"+strToday+"开始启用。") ;
				timer.scheduleAtFixedRate(tFileBuckup,bakDay,1000*60*60*intevHours);     // boom every .5sec starting now
			}
//			//添加半小时显示任务。  半小时任务提醒在配置文件中配置			
			//读取数据库，循环显示任务。
			// TODO: Add your code here
			String conf_prefix="A1";
			String id=null;
			String title=null;
			String awokeStyle =null;
			String initTimeStr=null;
			String nextTime=null;
			String intervalCode=null;
			long intervalNum;			//int   防止溢出问题
			String useful=null;
			String needAffirm=null;		//是否需要确认
			String content=null;
			sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
			int int_outtime=1 ;		// 过期的每隔6分钟安排一个
			
			long l_interval;
			long l_int;
			long l_begin;
			long l_today;
			Date dt_today=Calendar.getInstance().getTime();
			Date dt_begin=Calendar.getInstance().getTime();
			String taskInfo="";
			ArrayList awokeList=new ArrayList();
			Vector vector=new Vector();
			String str_today,str_begin;
				
//				//获取用户数据
				
				String sql = "";
				if (selectedType==null || selectedType.trim().equals("")) {
					sql = "SELECT ID, SortId, TITLE, BEGINTIME,NEXTTIME,ENDTIME,TIMETYPE" +
							", INTERVAL,INTERVALNUM, USEFUL, NEEDAFFIRM, CONTENT,AwokeStyle" +
							" FROM "+DirectorConstants.RMD_Awoke +
							//" Order by SortId asc, Id asc" +
							" Order by Nexttime asc";
					
				}else if(Reminder_Type_Garbage.equals(selectedType)){ //garbage
					sql="SELECT ID, SortId, TITLE, BEGINTIME,NEXTTIME,ENDTIME,TIMETYPE" +
							", INTERVAL,INTERVALNUM, USEFUL, NEEDAFFIRM, CONTENT,AwokeStyle" +
							" FROM "+DirectorConstants.RMD_Awoke +
							" WHERE Useful='N'"+
							//" Order by SortId asc, Id asc" +
							" Order by Nexttime asc";  //Interval='0' And 

				}else{  // some type
					sql="SELECT ID, SortId, TITLE, BEGINTIME,NEXTTIME,ENDTIME,TIMETYPE" +
							", INTERVAL,INTERVALNUM, USEFUL, NEEDAFFIRM, CONTENT,AwokeStyle" +
							" FROM "+DirectorConstants.RMD_Awoke +
							" WHERE TYPE LIKE '" + selectedType +"%'" +
							//" And Useful='Y'"+
							//" Order by SortId asc, Id asc" +
							" Order by Nexttime asc";		
				}
			
				rs=stmt.executeQuery( sql );
				
				while(rs.next()){

					//取配置信息
					id       = rs.getString("ID").toString();
					title       = rs.getString("TITLE").toString();
					awokeStyle       = rs.getString("AwokeStyle");
					
					// must using rs.getTimestamp(""),cann't be getTime("")(return is 1970-01-01) .
					initTimeStr   = sdf.format( rs.getTimestamp("BEGINTIME") );
					//System.out.println(" next 1" + title);

					//Time or Timestamp???
					//Time timAbc = rs.getTimestamp("NEXTTIME");
					Timestamp tim = rs.getTimestamp("NEXTTIME");
					if( tim!=null ){
						//System.out.println("get nextTIme" + tim );
						try {
							nextTime   = sdf.format( tim );
							//System.out.println("get success");
						} catch (Exception e) {
							// e.printStackTrace();
						}
					}

					//System.out.println("beginTime="+beginTime);		

					intervalCode    = rs.getString("INTERVAL").toString();
					
					intervalNum    = rs.getLong("INTERVALNUM") ;
					useful      = rs.getString("USEFUL").toString();
					needAffirm  = rs.getString("NEEDAFFIRM").toString();
					content     = rs.getString("CONTENT").toString();			
					
					
					// 采用数据库而不是XML文件之后，编码方式改变了，不需要转换了
//					title=StringUtils.toGB2312(title).trim();
//					content=StringUtils.toGB2312(content).trim();
					//System.out.println("title="+title);
					
					if(title==null||initTimeStr==null||intervalCode==null
							||useful==null||content==null||needAffirm==null
							||(useful.trim().toLowerCase().equals("n") && !Reminder_Type_Garbage.equals(selectedType))){
						//以下信息没有设置则不加入此提醒
						continue;					
					} 				

					intervalCode=intervalCode.trim();
					AwokeBean awokeBean=new AwokeBean();

					// 如果需要确认的已经过期，后面的循环处理。
					//System.out.println("interval="+interval);
					if(intervalCode.equals("0")){		//不循环					
						dt_begin=sdf.parse(initTimeStr);
						if(!Reminder_Type_Garbage.equals(selectedType) 
								&& dt_begin.before(dt_today)){
							continue;		//后面的处理,添加过期提醒
						}else{
							awokeBean.setThisBeginTime(dt_begin);
							awokeBean.setThisInterval(0);//暂定30*12							
						}

						// minute,hour,day
					} else {   // if(interval.equals("minute")) 每天 perDay   wzw on 2010-06-30改进	
						
						dt_begin = DirectorStringUtils.getNextBeginTime(initTimeStr, intervalCode, intervalNum);
						awokeBean.setThisBeginTime(dt_begin);
						//System.out.println(intervalNum +" "+DirectorConstants.intervalUintsOffsetMap.get(interval));
						awokeBean.setThisInterval(intervalNum * DirectorConstants.intervalUintsOffsetMap.get(intervalCode));//暂定30*12
						taskInfo= ("每" +intervalNum+ DirectorConstants.intervalUintsNameMap.get(intervalCode) +"循环，开始时间="+sdf.format(dt_begin));
					}
					
					awokeBean.setId(id);
					awokeBean.setTitle(title);
					awokeBean.setAwokeStyle(awokeStyle);
					awokeBean.setBeginTime(initTimeStr);
					awokeBean.setContent(content);
					awokeBean.setIntervalCode(intervalCode);
					awokeBean.setIntervalNum(intervalNum);
					awokeBean.setNeedAffirm(needAffirm);
					awokeBean.setUseful(useful);
					//System.out.println("title="+title);
					//System.out.println("needAffirm="+needAffirm);
					
					awokeList.add(awokeBean);
					//vector.add(awokeBean.getTitle());
					vector.add( new CodeNameBean(awokeBean.getId(),awokeBean.getTitle()));
					vector.add(sdf.format(awokeBean.getThisBeginTime()));
					vector.add(awokeBean.getContent());
					//加入到提醒序列中	
					if(awokeBean.getThisInterval()<1 && initTimer){	//一次性提醒
						log.info("Add: "+awokeBean.getTitle()+",一次性提醒,  interval="+ awokeBean.getThisInterval());
						timer.schedule(
								new TimerTask(Integer.parseInt(awokeBean.getId()), reducedAwokeBean(awokeBean),timer){
									public void run(){
										AwokeBean awbean=(AwokeBean)this.paramObject;
										log.info("Exec:"+awbean.getTitle());
										AwokeMessageDialog mw1=new AwokeMessageDialog(awbean,this.getTimer());
										//mw1.getCursor();
										mw1.setVisible(true);    
//										/// ComponentUtil.setLocationToCenter(mw1);			 
									}
								},
								awokeBean.getThisBeginTime()
						);
					}else if(initTimer){	//循环提醒					
						log.info("Add: "+awokeBean.getTitle()+","+taskInfo +"  interval="+ awokeBean.getThisInterval());
						timer.scheduleAtFixedRate(
								new TimerTask(Integer.parseInt(awokeBean.getId()),reducedAwokeBean(awokeBean),timer){
									public void run(){
										AwokeBean awbean=(AwokeBean)this.paramObject;
										log.info("Exec:"+awbean.getTitle());
										AwokeMessageDialog mw1=new AwokeMessageDialog(awbean,this.getTimer());
										//mw1.getCursor();
										mw1.setVisible(true);   
//										/// ComponentUtil.setLocationToCenter(mw1);	 
									}
								},
								awokeBean.getThisBeginTime(),
								awokeBean.getThisInterval()
						);     // boom every .5sec starting now
						
					}
					awokeBean = null;  //释放内存资源
				}
		
				//处理过期提醒，过期提醒不添加ID号,不删除，删除原提醒即可以删除相应的过期提醒。 
				rs.beforeFirst();
				while(rs.next()){

					dt_begin=Calendar.getInstance().getTime();
					id       = rs.getString("ID").toString();
					title       = rs.getString("TITLE").toString();
					awokeStyle = rs.getString("AwokeStyle");
					initTimeStr   = sdf.format( rs.getTimestamp("BEGINTIME") );
					//System.out.println(" next 1" + title);
					Timestamp tim = rs.getTimestamp("NEXTTIME");
					nextTime = null ;
					if( tim!=null ){
						//System.out.println("get nextTIme" + tim );
						try {
							nextTime   = sdf.format( tim );
							//System.out.println("get success");
						} catch (Exception e) {
							// e.printStackTrace();
						}
					}

					intervalCode    = rs.getString("INTERVAL").toString();
					
					intervalNum = rs.getLong("INTERVALNUM") ;
					useful      = rs.getString("USEFUL").toString();
					needAffirm  = rs.getString("NEEDAFFIRM").toString();
					content     = rs.getString("CONTENT").toString();

					if(title==null||initTimeStr==null||intervalCode==null||
							useful==null||content==null||needAffirm==null||
							useful.trim().toLowerCase().equals("n")){
						//以下信息没有设置则不加入此提醒
						continue;					
					} 				

					intervalCode=intervalCode.trim();
					AwokeBean awokeBean=new AwokeBean();
					
					// 如果需要确认的已经过期，添加过期提示
					if( needAffirm.trim().equals("Y") &&
						  ( ( nextTime!=null &&	sdf.parse(nextTime.trim()).before(Calendar.getInstance().getTime())) ||
						    ( nextTime==null &&	sdf.parse(initTimeStr.trim()).before(Calendar.getInstance().getTime()) )
						  )){
						//System.out.println(nextTime + " " + initTimeStr);
						if( nextTime==null )
							nextTime=initTimeStr;
						//System.out.println(" -2");
						
						Date t_today = Calendar.getInstance().getTime();
						dt_begin.setTime(t_today.getTime()+ 1000*60*(2*int_outtime+1) );//按3,5,7...排列
						int_outtime++;
						//对于过期提醒，不能设置 dt_begin值为将要发生时间，而是nextTime
						//	awokeBean.setThisBeginTime(dt_begin); 
						awokeBean.setThisBeginTime( sdf.parse(nextTime.trim()) );
						
						//awokeBean.setThisInterval(0);
												
						if(intervalCode.equals("0")){		//不循环
								awokeBean.setThisInterval(0);//暂定30*12							
						}else {//每天 per 	
							awokeBean.setThisInterval(intervalNum*
									DirectorConstants.intervalUintsOffsetMap.get(intervalCode));
						}
						
					} else {
						continue ;
					}
					
					awokeBean.setExpired(true);
					awokeBean.setId(id);
					awokeBean.setTitle( "[过期提醒] - "+title ); //+ " " +(nextTime==null?initTimeStr:nextTime)
					awokeBean.setAwokeStyle(awokeStyle);
					awokeBean.setBeginTime(initTimeStr);
					awokeBean.setContent(content);
					awokeBean.setIntervalCode(intervalCode);
					awokeBean.setIntervalNum(intervalNum);
					//System.out.println("title="+title);
					//System.out.println("needAffirm="+needAffirm);
					awokeBean.setNeedAffirm(needAffirm);
					awokeBean.setUseful(useful);
					
					awokeList.add(awokeBean);
					//vector.add(awokeBean.getTitle());
					vector.add( new CodeNameBean(awokeBean.getId(),awokeBean.getTitle()));
					vector.add(sdf.format(awokeBean.getThisBeginTime()));
					vector.add(awokeBean.getContent());
///					//加入到提醒序列中	
//					if(awokeBean.getThisInterval()<1 || 
//					      !awokeBena.isLoop() {	//一次性提醒
					if (initTimer) {
						log.info("Add: "+awokeBean.getTitle()+",一次性提醒,  interval="+ awokeBean.getThisInterval());
						timer.schedule(
								new TimerTask( reducedAwokeBean(awokeBean), timer){
									public void run(){
										AwokeBean awbean=(AwokeBean)this.paramObject;
										log.info("Exec:"+awbean.getTitle());
										AwokeMessageDialog mw1=new AwokeMessageDialog(awbean,this.getTimer());
										//mw1.getCursor();
										mw1.setVisible(true);    
//										/// ComponentUtil.setLocationToCenter(mw1);
									}
								},
								dt_begin //awokeBean.getThisBeginTime()
						);
					}
					
				}
				
			//设置JTable的内容
			Vector<String> vectorHeader =new Vector<String>();
			vectorHeader.add("名称");
			vectorHeader.add("提醒时间");
			vectorHeader.add("主要内容");
			vectorHeader.add("主要内容");
			vectorHeader.add("主要内容");
			//数据生成
			Object[][] data = null;
			if(selectedType==null || selectedType.trim().equals("")
					|| selectedType.trim().equals(Reminder_Type_AllCurrent) ){
				data = new Object[awokeList.size()+1][MainTable_Column_Count];
			}else{
				data = new Object[awokeList.size()][MainTable_Column_Count];
			}
			Object firstObj = null;
			String str_nextTime = null;
			for (int i = 0; i < awokeList.size(); i++) {			 
				if (((AwokeBean)awokeList.get(i)).getId()==null) {
					firstObj = ((AwokeBean)awokeList.get(i)).getTitle();
				}else{
					firstObj = new CodeNameBean( ((AwokeBean)awokeList.get(i)).getId(),
												((AwokeBean)awokeList.get(i)).getTitle(),
												((AwokeBean)awokeList.get(i)).isExpired());
				}
				data[i][MainTable_Column_Index_Name]= firstObj;
				str_nextTime = sdf.format(((AwokeBean)awokeList.get(i)).getThisBeginTime());
				data[i][MainTable_Column_Index_NextTime]=new CodeNameBean(str_nextTime, getRemainTimeNote(str_nextTime) );
				if (((AwokeBean)awokeList.get(i)).getIntervalNum()>0) {
					data[i][MainTable_Column_Index_Interval]=((AwokeBean)awokeList.get(i)).getIntervalNum()+"-"+((AwokeBean)awokeList.get(i)).getInterval();
				}else{
					data[i][MainTable_Column_Index_Interval]="";
				}
				data[i][MainTable_Column_Index_Confirm]=((AwokeBean)awokeList.get(i)).getNeedAffirm();
				data[i][MainTable_Column_Index_Content]=((AwokeBean)awokeList.get(i)).getContent();
			}
			if(selectedType==null || selectedType.trim().equals("")
					|| selectedType.trim().equals(Reminder_Type_AllCurrent)){
				data[awokeList.size()][MainTable_Column_Index_Name]="重要文件备份";
				str_nextTime = sdf.format(bakDay);
				data[awokeList.size()][MainTable_Column_Index_NextTime]=new CodeNameBean(str_nextTime, getRemainTimeNote(str_nextTime));
				data[awokeList.size()][MainTable_Column_Index_Interval]="1 day";
				data[awokeList.size()][MainTable_Column_Index_Confirm]="N";
				data[awokeList.size()][MainTable_Column_Index_Content]="重要文件备份，采用增量备份方式,系统备份终极解决方案。";
			}
			PlainTableModel ptm = this.getMainTable().getModel();
			ptm.removeAllRows();
			ptm.cancelSorting(); //clearSortingState();
			for (int i = 0; i < data.length; i++) {
				ptm.getTableModel().addRow(data[i]);
			}
//			setAllColWith(table);
			updateMainTable();
			
		} catch (Exception e){
			log.error (e);
		} finally {
			wzw.util.DbUtils.closeQuietly(conn, stmt, rs);
		}
	}

	private static String getRemainTimeNote(String str_nextTime) {
		try {

			//此处好像是去除0  
			Calendar today = Calendar.getInstance(); 
			Calendar old = Calendar.getInstance();
			sdfShort.applyPattern("yyyy-MM-dd");
			today.setTime( sdfShort.parse(sdfShort.format(today.getTime()).substring(0,10)) ); 
			old.setTime( sdfShort.parse(str_nextTime.substring(0,10)) ); 
			//老的时间减去今天的时间  
			long intervalMilli = old.getTime().getTime() - today.getTime().getTime();  
			//System.out.println(sdfShort.format(today.getTime()));
			//System.out.println(sdfShort.format(old.getTime()));
			//System.out.println(intervalMilli);
			//System.out.println((24 * 60 * 60 * 1000));
			int xcts = (int) (intervalMilli / (24 * 60 * 60 * 1000));  
			if (xcts==0) {
				return str_nextTime.substring(10).trim();
			}else if (xcts==1) {
				return str_nextTime.substring(10).trim()+"(明天)";
			}else if (xcts==2) {
				return str_nextTime.substring(10).trim()+"(后天)";
			}
			return str_nextTime.trim();
			
		} catch (ParseException e) {
			return str_nextTime.trim();
		}
	}

	public static void main(String[] args) {
		System.out.println( null instanceof CodeNameBean );
		System.out.println( null instanceof Double );
		System.out.println(getRemainTimeNote("2012-08-31 12:12:12"));
		System.out.println(getRemainTimeNote("2012-09-01 09:15:00"));
		System.out.println(getRemainTimeNote("2012-09-02 09:15:00"));
	}
	
	/**
	 * JTable的数据，展示改动影响较大，避免很多地方写相同代码，这里建一个公用方法供调用。
	 */
	public void updateMainTable(){
	    TableColumn tc = null;
	    TableColumnModel tcm = mainTable.getColumnModel(); 
        for(int i=0; i <MainTable_Columns_Width.length; i++)   {
            tc   =   tcm.getColumn(i);
            tc.setPreferredWidth(MainTable_Columns_Width[i]); 
        }

        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        
        // column size to CENTER
        tc = tcm.getColumn( MainTable_Column_Index_Confirm );//column name
        tc.setCellRenderer(renderer);
        tc = tcm.getColumn( MainTable_Column_Index_Interval );//column name
        tc.setCellRenderer(renderer);

		if ( (getMainTable().getModel()).isSorting()==false ) {
	    	(this.getMainTable().getModel()).setSortingStatus( MainTable_Column_Index_NextTime, PlainTableModel.ASCENDING);
		}
        this.getMainTable().showZebraCross();
	}
	
	public ReminderMainPanel(MainFrame mainFrame) { 
		super(mainFrame); 
		
		this.mainFrame = mainFrame;
		
		initializeInterface();
		
		this.update(null, null); //构建时候调用一次保险
		constructAfter();
	}

	public DirectorToolBar createToolBar() {
		this.toolBar = new ReminderToolBar( this );
		//this.setPreferredSize(new Dimension(20,25));
		this.toolBar.repaint();
		this.toolBar.validate();
		return this.toolBar; 
	}

	private JPopupMenu popupMenuForTree;
	private JMenuItem jpmi_Tree_AddNewAwoke;
	/**
	 * Table的弹出式菜单
	 */
	private JPopupMenu getPopupMenuForTree(){
		
		if(popupMenuForTree == null){
			popupMenuForTree = new JPopupMenu();

			jpmi_Tree_AddNewAwoke = new JMenuItem();
			jpmi_Tree_AddNewAwoke.setText("创建新提醒");
			jpmi_Tree_AddNewAwoke.addActionListener( this );
			
			popupMenuForTree.add( jpmi_Tree_AddNewAwoke );
		}
		return popupMenuForTree;		
	}
	 
	public DirectorMenuBar getMenuBar() {
		if (this.menuBar==null) {
			this.menuBar = new ReminderMenuBar( this );
			this.mainFrame.getLanguageManager().addObserver(menuBar);
		}
		return this.menuBar; 
	}

	private void initializeInterface(){
		
		final MainFrame topFrame =  mainFrame;
		this.setLayout(new BorderLayout());
		this.add( getToolBar(true), BorderLayout.NORTH);
		this.add( getMainSplitPane(), BorderLayout.CENTER);
		this.add( getStatusBar(true), BorderLayout.SOUTH);

		this.addKeyListener(this);
		
		currentStatusInfor = this.statusBar_currentAwokeAmount + getMainTable().getRowCount() ;
		setStatus(StatusBar_Index_One, currentStatusInfor);
		
		refreshView();
	}	
	
	public void refreshView(){
		super.refreshView();
		
		this.mainFrame.setJMenuBar( getMenuBar() );
		this.mainFrame.setToolBar( getToolBar() );
		
		// please do something in subclass.
		this.getMainTable().requestFocusInWindow ();
		
		//? wzw
		this.statusBar_currentAwokeAmount = I18nUtil.getBundleString( ReminderMainPanel.class, "statusBar_currentAwokeAmount.Text");    
		currentStatusInfor = this.statusBar_currentAwokeAmount + getMainTable().getRowCount() ;
		setStatus(StatusBar_Index_One, currentStatusInfor);
	}

	private JSplitPane getMainSplitPane(){
		if (mainSplitPane==null) {
			mainSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, false);
			mainSplitPane.add(getLeftScrollPane(),JSplitPane.LEFT);
			mainSplitPane.add(getRightSplitPane(), JSplitPane.RIGHT);
			
			// mainPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,false,getTree(),getTable());
			mainSplitPane.setDividerLocation( MainSplitPane_Left_Width );  //200);
		     
//			((JSplitPane)mainPanel).setBorder(null);
			// 设置JSplitPane是否可以展开或收起(如同文件总管一般)，设为true表示打开此功能。
			mainSplitPane.setOneTouchExpandable(true);
			// 设置分隔线宽度的大小，以pixel为计算单位。
			mainSplitPane.setDividerSize(6);

			//mainPanel.setLayout(null);
			//mainPanel.add(getLeftScrollPane(), null);
			//mainPanel.add(getRightScrollPanel(), null); 
		}
		return mainSplitPane;
	}
	 
	
    private class DirectorRenderer extends DefaultTreeCellRenderer {
        /**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		Icon tutorialIcon;

        public DirectorRenderer() {
            this(null) ;
        }
        
        public DirectorRenderer(Icon icon) {
            tutorialIcon = icon;
        }

        /** Returns an ImageIcon, or null if the path was invalid. */
        protected ImageIcon createImageIcon(String path) {
            //java.net.URL imgURL = MainFrame.class.getResource(path);
        	String imgURL = path;
            if (imgURL != null) {
                return new ImageIcon(imgURL);
            } else {
                System.err.println("Couldn't find file: " + path);
                return null;
            }
        }
        
        public Component getTreeCellRendererComponent(
                            JTree tree,
                            Object value,
                            boolean sel,
                            boolean expanded,
                            boolean leaf,
                            int row,
                            boolean hasFocus) {

            super.getTreeCellRendererComponent(
                            tree, value, sel,
                            expanded, leaf, row,
                            hasFocus);
            
            DefaultMutableTreeNode node = (DefaultMutableTreeNode)value; 
            //System.out.println(((CodeName)node.getUserObject()).getCode());
            String code = ((CodeNameBean)node.getUserObject()).getCode();
            if(code!=null){
            	if(code.equals(Reminder_Type_AllCurrent)){
            		setIcon( createImageIcon("./resource/tree_00.gif") );
            	} else if(code.equals("0000")){
            		setIcon( createImageIcon("./resource/tree_0000.gif") );
            	} else if(code.equals("0001")){
            		setIcon( createImageIcon("./resource/tree_0001.gif") );
            	} else if(code.equals("0002")){
            		setIcon( createImageIcon("./resource/tree_0002.gif") );
            	} else if(code.equals("0003")){
            		setIcon( createImageIcon("./resource/tree_0003.gif") );
            	} else if(code.equals("0004")){
            		setIcon( createImageIcon("./resource/tree_0004.gif") );
            	} else if(code.equals("0005")){
            		setIcon( createImageIcon("./resource/tree_0005.gif") );
            	} else if(code.equals(Reminder_Type_Garbage)){
            		setIcon( createImageIcon("./resource/tree_99.gif") );
            	} 
            }
            
            //System.out.println(ComponentUtil.getSelectedTreeNodeCode(tree)) ;            
            
            if (leaf ) {	// && isTutorialBook(value)
                //setIcon( createImageIcon("./resource/director.gif") );
                //setToolTipText("This book is in the Tutorial series.");
            } else {
                setToolTipText(null); //no tool tip
            }

            return this;
        }

//        protected boolean isTutorialBook(Object value) {
//            DefaultMutableTreeNode node =
//                    (DefaultMutableTreeNode)value;
//            BookInfo nodeInfo = 
//                    (BookInfo)(node.getUserObject());
//            String title = nodeInfo.bookName;
//            if (title.indexOf("Tutorial") >= 0) {
//                return true;
//            } 
//
//            return false;
//        }
    }



	 /**
	  * 删除，可以被主菜单、弹出式菜单、双击Table、单击按钮等调用，
	  * 		多个地方调用的写在一起，不要每个地方都写。
	  * @return
	  */
	 public void executeEditSelectedAwoke() {
		 	//set as current panel.
		 	this.mainFrame.getMainTabbedPane().setSelectedIndex(MainFrame.MainTabPane_ReminderMainPanel_Index);

		 	int row=getMainTable().getSelectedRow();
			if (row<0) {
				JOptionPane.showMessageDialog(this, msgDialog_plsSelectRow); //"请选择要修改的行！"
				return ;
			}
			Object obj = getMainTable().getValueAt( row,0);
			if( isAwokeChangable(obj)){  //obj instanceof CodeName){
				String id= ((CodeNameBean)(getMainTable().getValueAt( row,0))).getCode() ;

				AwokeEditDialog ap = new AwokeEditDialog(this.mainFrame, id);
				ComponentUtil.setLocationToCenter(this.mainFrame, ap);
				///ap.setModal(true); 
				ap.setVisible(true);
				
			}else{
				//"该条纪录是内置或者其他原因，不能修改。"  "错误"	
				JOptionPane.showMessageDialog(this, msgDialog_cannotChange, msgDialog_error, JOptionPane.ERROR_MESSAGE);
				return;
			}			
	 }
	 
	 
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	public void mouseReleased(MouseEvent e) {
		Object obj = e.getSource() ;
		if(obj==getMainTable()){
			// 在Table上右击鼠标
			//System.out.println ( " getPopupMenuForTable 1");
			if( e.getButton() == MouseEvent.BUTTON3 ) {	//显示弹出菜单
				
				//System.out.println (getTable().getX()+e.getX());
				//getPopupMenuForTable().locate( getTable().getX()+e.getX(), getTable().getY()+e.getY() );
				//getPopupMenuForTable().setVisible( true );
				getPopupMenuForTable().setSelected(null);
				getPopupMenuForTable().show( e.getComponent(), e.getX(), e.getY() );
				
			}
		}
		
	}

	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	public void actionPerformed(ActionEvent e) {
		super.actionPerformed(e);
		
		Object obj=e.getSource();
		// toolBar
		if( obj == this.menuBar.jmi_Edit_NewAwoke
				|| obj==this.toolBar.tb_creatAwoke
				|| obj==jpmi_MainTable_New
				|| obj== jpmi_Tree_AddNewAwoke){		// 主菜单、弹出式菜单
			this.executeAddNewAwoke();
		
		} else if( obj == this.menuBar.jmi_Edit_ModAwoke
					|| obj==this.toolBar.tb_modAwoke
					|| obj==jpmi_MainTable_Edit){
			this.executeEditSelectedAwoke();
			
		} else if(obj == this.menuBar.jmi_Edit_DelAwoke
					|| obj==jpmi_MainTable_Delete){
			executeDeleteSelectedAwoke();
			
		} else if(obj == jpmi_MainTable_Disable ){
			executeDisableSelectedAwoke();	 
			
		} else if(obj == jpmi_MainTable_Search ){
			this.getRightSplitPane().setDividerLocation(CommonSearchable.CommonSearchPanel_Hight);
			this.getCommonSearchPanel().getKeywordTextField().requestFocusInWindow();
			
		} else if(obj == jpmi_MainTable_Refresh ){
			try {
				fetchData();				
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			
		} else if(obj == this.menuBar.jmi_Edit_TestAwoke 
					|| obj==jpmi_MainTable_Test){
			executeTestSelectedAwoke();
			
		}
	}


	//mouse event for tree.
	public void tree_mouseReleased(MouseEvent e) {
		Object obj = e.getSource() ;
		if(obj==getTree()){ 
			if( e.getButton() == MouseEvent.BUTTON3 ) {	//显示弹出菜单 
				getPopupMenuForTree().setSelected(null);
				getPopupMenuForTree().show( e.getComponent(), e.getX(), e.getY() );
			}
		}
	}

	public void tree_mouseClicked(MouseEvent e) {
		if(!e.isPopupTrigger() && (e.getClickCount()==2||e.getClickCount()==1) ) {

			//ComponentUtil.setPoolName(" main"  );
			//ComponentUtil.initTable(getTable(),"SELECT TITLE, format(BEGINTIME,'yyyy-mm-dd hh:mm:ss') as BGTIME,CONTENT FROM AWOKE WHERE TYPE LIKE '" + 
			//		ComponentUtil.getSelectedTreeNodeCode(getTree())+"%'",false);

			DefaultTableModel dtm =  (this.getMainTable().getModel()).getTableModel();
			Vector v_colName=new Vector();
			v_colName.add("名称");
			v_colName.add("提醒时间");
			v_colName.add("主要内容");
		
			Vector v_data=new Vector();
			Connection conn=null; 
			Statement stmt=null;
			ResultSet rs=null;
			String sql ="";
			try {
				String selectedType = ComponentUtil.getSelectedTreeNodeCode(getTree());
				if (selectedType==null || selectedType.trim().equals("")) {
					return ;   // 2007-9 added by wzw.
				}else if(Reminder_Type_Garbage.equals(selectedType)){
					sql="SELECT ID,SortId,TITLE, format(BEGINTIME,'yyyy-mm-dd hh:mm:ss') as BGTIME" +
							",Interval,IntervalNum,CONTENT" +
							" FROM "+DirectorConstants.RMD_Awoke +
							" WHERE Useful='N'";  //Interval='0' And 
				}else{
					sql="SELECT ID,SortId,TITLE, format(BEGINTIME,'yyyy-mm-dd hh:mm:ss') as BGTIME" +
							",Interval,IntervalNum,CONTENT" +
							" FROM "+DirectorConstants.RMD_Awoke +
							" WHERE TYPE LIKE '" + selectedType +"%'" +
							" And Useful='Y'";		
				}
				conn= ApplicationContext.getInstance().getDataSourceManager().getConnection();
				stmt=conn.createStatement();
				log.info(sql);
				rs=stmt.executeQuery(sql);
				int id ;
				String title="";
				String bgTime="";
				String content="";
				Date bgDate = null;
				while(rs.next()){
					id = rs.getInt( "ID" );
					title = rs.getString( "TITLE" );
					bgTime = rs.getString( "BGTIME" );
					bgDate = DirectorStringUtils.getNextBeginTime(bgTime, rs.getString("Interval"), rs.getLong("IntervalNum"));
					bgTime = Formatter.format(bgDate,"yyyy-MM-dd HH:mm:ss");
					content = rs.getString( "CONTENT" );
 
					Vector tv_row = new Vector();
					tv_row.add( new CodeNameBean(id+"", title) ) ;
					tv_row.add( bgTime );
					tv_row.add( content);
					
					v_data.add( tv_row );
				}

			} catch (SQLException e1) {
				//"查询失败"
				JOptionPane.showMessageDialog(this,e1.getMessage(),msgDialog_errorDbQuery,JOptionPane.ERROR_MESSAGE);
				e1.printStackTrace();			
				
			}  catch (Exception e1) {
				//"执行失败"
				JOptionPane.showMessageDialog(this,e1.getMessage(),msgDialog_errorDbUpdate,JOptionPane.ERROR_MESSAGE);
				e1.printStackTrace();						

			} finally{
				//释放资源
				wzw.util.DbUtils.closeQuietly(conn, stmt, rs);
			}
			
//			dtm.setDataVector(v_data,v_colName);
			updateMainTable();
						
			// 所有提醒在启动时初始了，不改变，这里只过滤，改变显示
			try {
				this.fetchData();
				//this.tasksInit( ComponentUtil.getSelectedTreeNodeCode(getTree()), false );
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			//return ;
		}

		currentStatusInfor = this.statusBar_currentAwokeAmount + getMainTable().getRowCount() ; //"Current awoke amount is : " 
		setStatus(StatusBar_Index_One, currentStatusInfor);
	}

	public void doRefresh() {
		leftScrollPanel.setViewportView(getTree());
		rightScrollPanel.setViewportView(getMainTable());	
		
	}

	public static String toCSV(int[] ids) {

		final int size = ids.length;

		if (size < 1)
			return "";

		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < size; i++) {
			int obj = ids[i];
			sb.append(obj);
			if (i < size - 1)
				sb.append(",");
		}

		return sb.toString();
	}
	
	/**
	 * 
	 * <p>Does this awoke be editable or deleted.</p>
	 * @author Zeven on 2008-5-27
	 * @param obj
	 * @return
	 */
	public static boolean isAwokeChangable(Object obj){
		if(obj instanceof CodeNameBean){
			return true;
//			//String name = ((CodeName)obj).getName();
//			if (obj!=null && ((CodeNameBean)obj).isBoolFlag1()) {
//				return false;   //awoke is expired.
//			}else{
//				return true;
//			}
			
		}else{
			return false;   //not CodeName object.
		}
	}
	
	 /**
	  * 批量停用提醒，可以被主菜单、弹出式菜单、按钮等调用。
	  * @return
	  */
	 public void executeDisableSelectedAwoke() {
		 //step: check input.
	 	int[] rows=getMainTable().getSelectedRows(); //getSelectedRow();
		int selRowCount = rows.length;
	 	if (selRowCount<1) {
			//"请选择要删除的行！"
			JOptionPane.showMessageDialog(this, msgDialog_plsSelectRow);
			return ;
		}
		
		//step: confirm action.
		int row;
		Object obj = null;
		int[] ids = new int[rows.length];
		for (int i = 0; i < rows.length; i++) {
			row = rows[i];
			obj = getMainTable().getValueAt( row,0);
			if( isAwokeChangable(obj)){ //obj instanceof CodeName){
				int id= Integer.parseInt( ((CodeNameBean)(getMainTable().getValueAt( row,0))).getCode() );
				ids[i] = id;   //id数组
			} else{
				//"记录["+ obj.toString() +"]是内置或者其他原因，不能删除!" "错误"
				JOptionPane.showMessageDialog(this, "包含的内置的提醒["
							+getMainTable().getValueAt( row,MainTable_Column_Index_Name)
						    +"]，不能停用。", msgDialog_error,JOptionPane.ERROR_MESSAGE);
				return;
			}
		}

		//"确认删除当前选中的["+rows.length+"]条记录吗？删除后不能找回！"
		String tmp_msg = "确定要停用选中的提醒吗？";
		if(JOptionPane.showConfirmDialog(this, tmp_msg, msgDialog_error,JOptionPane.OK_CANCEL_OPTION)
				!=JOptionPane.OK_OPTION)
			return;
		
		//step: write to db
		//DbBean dbBean = new DbBean(DbBean.DefaultPoolName);
		ReminderDao rd = new ReminderDaoImpl();
		try {			
			rd.disableReminderByIds(ids);

			fetchData(); //刷新数据
		} catch (SQLException e) {
			JOptionPane.showMessageDialog(this,e.getMessage(),"数据库操作失败",JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();
		}			
	 }
	
	 /**
	  * 删除，可以被主菜单、弹出式菜单、按钮等调用。
	  * @return
	  */
	 public void executeDeleteSelectedAwoke() {
		 //step: check input.
	 	int[] rows=getMainTable().getSelectedRows(); //getSelectedRow();
		int selRowCount = rows.length;
	 	if (selRowCount<1) {
			//"请选择要删除的行！"
			JOptionPane.showMessageDialog(this, msgDialog_plsSelectRow);
			return ;
		}
		
		//step: confirm action.
		int row;
		Object obj = null;
		int[] ids = new int[rows.length];
		for (int i = 0; i < rows.length; i++) {
			row = rows[i];
			obj = getMainTable().getValueAt( row,0);
			if( isAwokeChangable(obj)){ //obj instanceof CodeName){
				int id= Integer.parseInt( ((CodeNameBean)(getMainTable().getValueAt( row,0))).getCode() );
				ids[i] = id;   //id数组
			}else{
				//"记录["+ obj.toString() +"]是内置或者其他原因，不能删除!" "错误"
				JOptionPane.showMessageDialog(this, msgDialog_cannotDelete, msgDialog_error,JOptionPane.ERROR_MESSAGE);
				return;
			}
		}

		//"确认删除当前选中的["+rows.length+"]条记录吗？删除后不能找回！"
		String tmp_msg = StringUtils.replace(msgDialog_infoDelete, "${rowSize}", selRowCount+"");
		if(JOptionPane.showConfirmDialog(this, tmp_msg, msgDialog_error,JOptionPane.OK_CANCEL_OPTION)
				!=JOptionPane.OK_OPTION)
			return;
		
		//step: write to db
		//DbBean dbBean = new DbBean(DbBean.DefaultPoolName);
		ReminderDao rd = new ReminderDaoImpl();
		try {			
			rd.deleteReminderByIds(ids);
			
			PlainTableModel ptm = this.getMainTable().getModel() ;
			DefaultTableModel tableModel = ptm.getTableModel();
			for (int i=rows.length-1; i>-1; i--) {
				//tableModel.removeRow( rows[i] );  //根据row number删除界面显示,从后往前删除。
				ptm.removeRow( rows[i] );
				timer.removeTask( ids[i] ) ; //根据id删除工作
			}
			currentStatusInfor = this.statusBar_currentAwokeAmount + getMainTable().getRowCount() ;
			setStatus(StatusBar_Index_One, currentStatusInfor);
			JOptionPane.showMessageDialog(this, msgDialog_infoDeleteSuccess);//"删除成功！"
			
		} catch (SQLException e) {
			JOptionPane.showMessageDialog(this,e.getMessage(),"数据库操作失败",JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();
		}			
	 }

	 
	 /**
	  * 测试当前选择的提醒，可以被主菜单、弹出式菜单、按钮等调用。
	  * @return
	  */
	 public void executeTestSelectedAwoke() {
			
		int row=getMainTable().getSelectedRow();
		if (row<0) {
			JOptionPane.showMessageDialog(this, msgDialog_plsSelectRow);
			return ;
		}
		Object obj = getMainTable().getValueAt( row,0);
		String id = "-1";
		if(obj instanceof CodeNameBean){
			id= ((CodeNameBean)(getMainTable().getValueAt( row,0))).getCode() ;
			
		}else{
			JOptionPane.showMessageDialog(this, msgDialog_cannotTest);//"该条纪录是内置或者其他原因，不能测试。"
			return;
		}
			
		 executeTestSelectedAwoke( id );
	 }

	 public void executeTestSelectedAwoke( String id ) {
			
			// 获取 id 之后，根据id生成一个消息框
			log.info("Add: 加入一个测试的提醒");
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			AwokeBean awokeBean = new AwokeBean();
		
			Connection conn=null;
			Statement stmt=null;
			ResultSet rs=null;
			String sql=null;
			try {
				conn= ApplicationContext.getInstance().getDataSourceManager().getConnection();
				sql="SELECT ID, SortId, TITLE, BEGINTIME,NEXTTIME,ENDTIME,TIMETYPE, INTERVAL,INTERVALNUM, USEFUL, NEEDAFFIRM, CONTENT,AwokeStyle FROM "+DirectorConstants.RMD_Awoke+" WHERE ID="+id;
				stmt=conn.createStatement();
				rs=stmt.executeQuery(sql);
				if(rs.next()){

					awokeBean.setTest( true );
					awokeBean.setId( rs.getInt("ID")+"" );
					awokeBean.setTitle("测试提醒 "+ rs.getString("TITLE") );
					awokeBean.setAwokeStyle(rs.getString("AwokeStyle"));
					awokeBean.setBeginTime( sdf.format( rs.getTimestamp("BEGINTIME")) );
					Date td_beginTime = Calendar.getInstance().getTime();
					td_beginTime.setTime( td_beginTime.getTime()+500 );
					awokeBean.setThisBeginTime( td_beginTime );
					awokeBean.setContent( rs.getString("CONTENT") );
					awokeBean.setIntervalCode( "year" );	//interval // 不使用"0"
					awokeBean.setIntervalNum( rs.getLong("INTERVALNUM") );
					//System.out.println("title="+title);
					//System.out.println("needAffirm="+needAffirm);
					awokeBean.setNeedAffirm( rs.getString("NEEDAFFIRM") );
					awokeBean.setUseful( rs.getString("USEFUL") );
					
				}else{
					JOptionPane.showMessageDialog(this,"数据库没有相应的信息！","错误",JOptionPane.ERROR_MESSAGE);
					return ;
				}

			} catch (SQLException e1) {
				JOptionPane.showMessageDialog(this,e1.getMessage(),"查询失败",JOptionPane.ERROR_MESSAGE);
				e1.printStackTrace();						
			} finally{
				//释放资源
				wzw.util.DbUtils.closeQuietly(conn, stmt, rs);
			}
			
			timer.schedule(
					new TimerTask( reducedAwokeBean(awokeBean), timer){
						public void run(){
							AwokeBean awbean=(AwokeBean)this.paramObject;
							log.info("Exec:"+awbean.getTitle());
							AwokeMessageDialog mw1=new AwokeMessageDialog(awbean,this.getTimer());
							//mw1.getCursor();
							mw1.setVisible(true);    
//							/// ComponentUtil.setLocationToCenter(mw1);			 
						}
					},
					awokeBean.getThisBeginTime()
			);
			awokeBean = null;  //释放内存资源
	 }

		/**
		 *
		 */
	@SuppressWarnings("unused")
	public void addNewAwoke(String id,
							String title,
							String beginTime,
							String interval,
							long intervalNum,
							String useful,
							String needAffirm,
							String content,
							String awokeStyle) throws Exception{

		//id       = rs.getString("ID").toString();
		//title       = rs.getString("TITLE").toString();
		//beginTime   = sdf.format( rs.getTimestamp("BEGINTIME") );
		Timestamp tim = null; //rs.getTimestamp("NEXTTIME");
		String nextTime = "";
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if( tim!=null ){
			//System.out.println("get nextTIme" + tim );
			try {
				nextTime   = sdf.format( tim );
				//System.out.println("get success");
			} catch (Exception e) {
				// e.printStackTrace();
			}
		}
		//interval    = rs.getString("INTERVAL").toString();		
		//intervalNum    = rs.getInt("INTERVALNUM") ;
		//useful      = rs.getString("USEFUL").toString();
		//needAffirm  = rs.getString("NEEDAFFIRM").toString();
		//content     = rs.getString("CONTENT").toString();
		//interval=interval.trim();
	
		if(title==null||beginTime==null||interval==null
				||useful==null||content==null||needAffirm==null){ //||useful.trim().toLowerCase().equals("n")
			//以下信息没有设置则不加入此提醒
			throw new Exception("信息不完整！");					
		} 				
	
		AwokeBean awokeBean=new AwokeBean();
		
		// 如果需要确认的已经过期，后面的循环处理。
		Date dt_begin = Calendar.getInstance().getTime();
		Date dt_today = Calendar.getInstance().getTime();
		long l_begin ;
		long l_today ;
		long l_int;
		long l_interval;
		String taskInfo="";

		String initTimeStr = beginTime;
		String intervalCode = interval;
		if(intervalCode.equals("0")){		//不循环					
			dt_begin=sdf.parse(beginTime);
			if(dt_begin.before(dt_today) && !useful.trim().toLowerCase().equals("n")){
				throw new Exception("错误，永远不会执行的提醒！(提示：修改开始时间，或取消'提醒有效'选项)");
			}else{
				awokeBean.setThisBeginTime(dt_begin);
				awokeBean.setThisInterval(0);//暂定30*12							
			}

			// minute,hour,day
		} else {
			dt_begin = DirectorStringUtils.getNextBeginTime(initTimeStr, intervalCode, intervalNum);
			awokeBean.setThisBeginTime(dt_begin);
			//System.out.println(intervalNum +" "+DirectorConstants.intervalUintsOffsetMap.get(interval));
			awokeBean.setThisInterval(intervalNum * DirectorConstants.intervalUintsOffsetMap.get(intervalCode));//暂定30*12
			taskInfo= ("每" +intervalNum+ DirectorConstants.intervalUintsNameMap.get(intervalCode) +"循环，开始时间="+sdf.format(dt_begin));
		}
		
		//下面的算法被替换为更简单的。		
		awokeBean.setId(id);
		awokeBean.setTitle(title);
		awokeBean.setAwokeStyle(awokeStyle);
		awokeBean.setBeginTime(beginTime);
		awokeBean.setContent(content);
		awokeBean.setIntervalCode(interval);
		awokeBean.setIntervalNum(intervalNum);
		//System.out.println("title="+title);
		//System.out.println("needAffirm="+needAffirm);
		awokeBean.setNeedAffirm(needAffirm);
		awokeBean.setUseful(useful);
		
		//awokeList.add(awokeBean);
		
		//vector.add(awokeBean.getTitle());
		Vector<Object> vector = new Vector<Object>();
		vector.add( new CodeNameBean(awokeBean.getId(), awokeBean.getTitle()));
//		vector.add(sdf.format(awokeBean.getThisBeginTime()));   //thisBeginTime
		String str_nextTime = sdf.format(awokeBean.getThisBeginTime());
		vector.add(new CodeNameBean(str_nextTime, getRemainTimeNote(str_nextTime) ) );   //thisBeginTime
		if (awokeBean.getIntervalNum()>0) {
			vector.add(awokeBean.getIntervalNum()+"-"+awokeBean.getInterval());
		}else{
			vector.add(" ");
		}	
		vector.add(awokeBean.getNeedAffirm());
		vector.add(awokeBean.getContent());
		//加入到提醒序列中	
		if(!useful.trim().toLowerCase().equals("n") && awokeBean.getThisInterval()<1){	//一次性提醒
			log.info("Add: "+awokeBean.getTitle()+",一次性提醒,  interval="+ awokeBean.getThisInterval());
			timer.schedule(
					new TimerTask(Integer.parseInt(awokeBean.getId()), reducedAwokeBean(awokeBean),timer){
						public void run(){
							AwokeBean awbean=(AwokeBean)this.paramObject;
							log.info("Exec:"+awbean.getTitle());
							AwokeMessageDialog mw1=new AwokeMessageDialog(awbean,this.getTimer());
							//mw1.getCursor();
							mw1.setVisible(true);    
//							/// ComponentUtil.setLocationToCenter(mw1);				 
						}
					},
					awokeBean.getThisBeginTime()
			);
		}else if(!useful.trim().toLowerCase().equals("n")){	//循环提醒					
			log.info("Add: "+awokeBean.getTitle()+","+taskInfo +"  interval="+ awokeBean.getThisInterval());
			timer.scheduleAtFixedRate(
					new TimerTask(Integer.parseInt(awokeBean.getId()), reducedAwokeBean(awokeBean),timer){
						public void run(){
							AwokeBean awbean=(AwokeBean)this.paramObject;
							log.info("Exec:"+awbean.getTitle());
							AwokeMessageDialog mw1=new AwokeMessageDialog(awbean,this.getTimer());
							//mw1.getCursor();
							mw1.setVisible(true);   
//							/// ComponentUtil.setLocationToCenter(mw1);				 
						}
					},
					awokeBean.getThisBeginTime(),
					awokeBean.getThisInterval()
			);     // boom every .5sec starting now
			
		}
		(this.getMainTable().getModel()).getTableModel().addRow( vector );
		DirectorComponentUtils.selectMatchedRows(this.getMainTable(), MainTable_Column_Index_Name, vector.get(0));

		currentStatusInfor = this.statusBar_currentAwokeAmount + getMainTable().getRowCount() ;
		setStatus(StatusBar_Index_One, currentStatusInfor);
	}

	private AwokeBean reducedAwokeBean(AwokeBean awokeBean) {
		AwokeBean bean = new AwokeBean();
		bean.setId( awokeBean.getId());
		bean.setTest( awokeBean.isTest() );
		bean.setTitle( awokeBean.getTitle() );
		bean.setThisInterval( awokeBean.getThisInterval());
		bean.setThisBeginTime( awokeBean.getThisBeginTime());		
		bean.setIntervalCode( awokeBean.getInterval());
		bean.setIntervalNum( awokeBean.getIntervalNum() );
		bean.setExpired( awokeBean.isExpired() );
		bean.setBeginTime( awokeBean.getBeginTime() );
		//bean.setNextTime( awokeBean.getNextTime());
		
		return bean;
	}

	private String statusBar_currentAwokeAmount = "";     //Current a awoke amount is : 
	private String msgDialog_cannotChange = null;    
	private String msgDialog_cannotDelete = null;    
	private String msgDialog_cannotTest = null;     

	public void update(Observable o, Object arg) {
		super.update(o, arg);
		
		ResourceBundle bundle = I18nUtils.getBundle(DirectorConstants.I18n_Language_Name);

		//I18nUtil.getBundleString(bundle, MainFrame.class, "tab.reminderMainPanel.Text")
		// Tree
	    //((CodeName)root.getUserObject()).setName(I18nUtil.getBundleString(bundle, MainFrame.class, "tree.00.Text"));
	    ((CodeNameBean)dir.getUserObject()).setName(I18nUtil.getBundleString(bundle, ReminderMainPanel.class, "tree.00.Text"));
	    ((CodeNameBean)ord.getUserObject()).setName(I18nUtil.getBundleString(bundle, ReminderMainPanel.class, "tree.0000.Text"));
	    ((CodeNameBean)imp.getUserObject()).setName(I18nUtil.getBundleString(bundle, ReminderMainPanel.class, "tree.0001.Text"));
	    ((CodeNameBean)bri.getUserObject()).setName(I18nUtil.getBundleString(bundle, ReminderMainPanel.class, "tree.0002.Text"));
	    ((CodeNameBean)ply.getUserObject()).setName(I18nUtil.getBundleString(bundle, ReminderMainPanel.class, "tree.0003.Text"));
	    ((CodeNameBean)ait.getUserObject()).setName(I18nUtil.getBundleString(bundle, ReminderMainPanel.class, "tree.0004.Text"));
	    ((CodeNameBean)els.getUserObject()).setName(I18nUtil.getBundleString(bundle, ReminderMainPanel.class, "tree.0005.Text"));
	    ((CodeNameBean)gbg.getUserObject()).setName(I18nUtil.getBundleString(bundle, ReminderMainPanel.class, "tree.99.Text"));
	    getTree().updateUI(); //解决jtree节点显示不全问题，后面带省略号
	    
	    //table
	    Vector<String> columnIdentifiers = new Vector<String>();
	    columnIdentifiers.add(I18nUtil.getBundleString(bundle, ReminderMainPanel.class, "table.col01.Text"));
	    columnIdentifiers.add(I18nUtil.getBundleString(bundle, ReminderMainPanel.class, "table.col02.Text"));
	    columnIdentifiers.add(I18nUtil.getBundleString(bundle, ReminderMainPanel.class, "table.col03.Text"));
	    columnIdentifiers.add(I18nUtil.getBundleString(bundle, ReminderMainPanel.class, "table.col04.Text"));
	    columnIdentifiers.add(I18nUtil.getBundleString(bundle, ReminderMainPanel.class, "table.col05.Text"));
	    DefaultTableModel dtm = (this.getMainTable().getModel()).getTableModel();
	    dtm.setColumnIdentifiers(columnIdentifiers);
	    
	    //resize table columns
	    updateMainTable();
        
        //popup menu for table
        this.getPopupMenuForTable();  //create object first
        this.getPopupMenuForTree();  //create object first
        jpmi_MainTable_New.setText(I18nUtil.getBundleString(bundle, ReminderMainPanel.class, "jpmi_MainTable_New.Text"));
        jpmi_MainTable_Edit.setText(I18nUtil.getBundleString(bundle, ReminderMainPanel.class, "jpmi_MainTable_Edit.Text"));
        jpmi_MainTable_Delete.setText(I18nUtil.getBundleString(bundle, ReminderMainPanel.class, "jpmi_MainTable_Delete.Text"));
        jpmi_MainTable_Test.setText(I18nUtil.getBundleString(bundle, ReminderMainPanel.class, "jpmi_MainTable_Test.Text"));
        // using common text of DirectorPanel.class
        jpmi_MainTable_Search.setText(I18nUtil.getBundleString(bundle, DirectorPanel.class, "jpmi_MainTable_Search.Text"));
        jpmi_MainTable_Refresh.setText(I18nUtil.getBundleString(bundle, DirectorPanel.class, "jpmi_MainTable_Refresh.Text"));
        jpmi_Tree_AddNewAwoke.setText(I18nUtil.getBundleString(bundle, ReminderMainPanel.class, "jpmi_Tree_AddNewAwoke.Text"));
        
        String className = ReminderMainPanel.class.getName();
        statusBar_currentAwokeAmount = I18nUtil.getBundleString(bundle, className, "statusBar_currentAwokeAmount.Text");    
		//msgDialog_backupFail = I18nUtil.getBundleString(bundle, className, "msgDialog_backupFail.Message");  // 不用  
		msgDialog_cannotChange = I18nUtil.getBundleString(bundle, className, "msgDialog_cannotChange.Message");    
		msgDialog_cannotDelete = I18nUtil.getBundleString(bundle, className, "msgDialog_cannotDelete.Message");    
		msgDialog_cannotTest = I18nUtil.getBundleString(bundle, className, "msgDialog_cannotTest.Message");     
		
		this.currentStatusInfor = this.statusBar_currentAwokeAmount+this.getMainTable().getRowCount();
		///this.setStatus(StatusBar_Index_One, this.currentStatusInfor);
	
		//更新主菜单、工具栏、状态栏 -如果需要放到MainPanel的update方法中去
		//this.getMenuBar().update(null, null);
		this.getToolBar().update(null, null);  //目前各MainPanel的toolBar一样，所以以这个更新，其他地方不处理
		
	} 

	public void removeAwoke(int id) {
		timer.removeTask(id );
		
	}


    /**
	 * <p>
	 * fetchData:从数据库获取数据，并且在界面做展示控制。
	 * setupView:不从数据库获取数据，只是做见面展示控制。
	 * </p>
	 * 
     */
	public void setupView() {
		DirectorComponentUtils.scrollToRow( getMainTable(), 0);  //
		
		//set selected
		if( this.searchPanel.executeSearch()<1 
				&& getMainTable().getRowCount()>0) {
	        getMainTable().setRowSelectionInterval(0, 0);
		}

		currentStatusInfor = this.statusBar_currentAwokeAmount + getMainTable().getRowCount() ; //"Current awoke amount is : " 
		setStatus(StatusBar_Index_One, currentStatusInfor);
	}
	
	@Override
	public boolean fetchData() throws SQLException  {
		try {
			this.initTasksInfo( ComponentUtil.getSelectedTreeNodeCode(getTree()), false );
		
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		setupView();
		return true;
	}

	@Override
	public boolean saveData() throws SQLException  {
		// TODO Auto-generated method stub
		return false;
	}

	public void mouseClicked(MouseEvent e) {
		Object obj = e.getSource() ;
		if(obj==getMainTable()){
			// 双击
			if(!e.isPopupTrigger() && e.getClickCount()==2) {
				executeEditSelectedAwoke();
			}
		}
	}

	public void closeCommonSearchPanel() {
		this.getRightSplitPane().setDividerLocation(0);
		this.getMainTable().requestFocusInWindow();
	}

	public void keyPressed(KeyEvent e) {
		int keyCode = e.getKeyCode();
		Object obj = e.getSource();
		
		//System.out.println("11111111111111--"+e.getKeyCode());
	    if (keyCode == KeyEvent.VK_F && e.isControlDown()
	    		&& (obj==this.getMainTable() || obj==this || obj==this.getTree()) ) {
			this.getRightSplitPane().setDividerLocation(CommonSearchPanel_Hight);
			this.getCommonSearchPanel().getKeywordTextField().requestFocusInWindow();
	    	e.consume();
	    	
		}else if(e.getKeyCode() == KeyEvent.VK_F5
	    		&& (obj==mainTable||obj==tree) ){ //refresh
	    	try {
				fetchData();
				
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
	    	e.consume();
	    	
	    }
	}

	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}

	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}

	public Timer getTimer() {
		return timer;
	}

	public void setTimer(Timer timer) {
		this.timer = timer;
	}

	@Override
	public void mouseDragged(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseMoved(MouseEvent e) {
		Object eventObj = e.getSource();
		if (eventObj == getMainTable()) {
	        String tipStr=null;
			int row = getMainTable().rowAtPoint(e.getPoint());
	        int column = getMainTable().columnAtPoint(e.getPoint());
	        if (column==MainTable_Column_Index_Name
	        		||column==MainTable_Column_Index_NextTime
	        		||column==MainTable_Column_Index_Content) {
		        Object val=getMainTable().getValueAt(row, column);
		        if (val!=null) {
		        	if (column==MainTable_Column_Index_NextTime){  //val instanceof CodeNameBean) {
		        		tipStr = ((CodeNameBean)val).getCode();
					}else{
						tipStr = val.toString();
					}
				}
			}
	        if( tipStr!=null && "".equals(tipStr.trim()) ){
	        	tipStr = null;
	        }
        	getMainTable().setToolTipText(tipStr);
		}
	}

	
}  //  @jve:decl-index=0:visual-constraint="10,10"


class MainFrame_tree_mouseAdapter extends java.awt.event.MouseAdapter {
	ReminderMainPanel adaptee;

	MainFrame_tree_mouseAdapter(ReminderMainPanel reminderMainPanel) {
		this.adaptee = reminderMainPanel;
	}
	public void mouseReleased(MouseEvent e) {
		adaptee.tree_mouseReleased(e);
	}
	public void mouseClicked(MouseEvent e){
		adaptee.tree_mouseClicked(e);
		e.consume();

		return ;
	}
	
	/**
	 * <p>java method describe</p>
	 * @author Zeven on 2006-2-25
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(Calendar.getInstance().getTime());
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Calendar.getInstance().getTime());
	}
}
